<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>双栏Markdown转图片工具</title>
    <script src="/static/js/marked.min.js"></script>
    <script src="/static/js/html2canvas.min.js"></script>
    <script src="/static/js/chroma.min.js"></script>
    <style>
        /* 定义字体 */
        @font-face {
            font-family: 'Arial';
            src: local('Arial');
        }
        @font-face {
            font-family: 'Microsoft YaHei';
            src: url('/static/fonts/msyh.ttc');
        }
        @font-face {
            font-family: 'SimSun';
            src: url('/static/fonts/simsun.ttc');
        }
        @font-face {
            font-family: 'KaiTi';
            src: url('/static/fonts/simkai.ttf');
        }
        @font-face {
            font-family: 'FangSong';
            src: url('/static/fonts/simfang.ttf');
        }
        @font-face {
            font-family: 'SimHei';
            src: url('/static/fonts/SIMHEI.TTF');
        }
        @font-face {
            font-family: 'Times New Roman';
            src: url('/static/fonts/times.ttf');
        }

        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            display: flex;
            gap: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .input-section {
            flex: 1;
            min-width: 400px;
        }
        
        .output-section {
            flex: 1;
            min-width: 500px;
        }
        
        .dual-input-container {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .input-column {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        
        .input-column-left {
            flex: 0.6; /* 左栏60%宽度 */
        }
        
        .input-column-right {
            flex: 0.4; /* 右栏40%宽度 */
        }
        
        .column-label {
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
        }
        
        textarea {
            width: 100%;
            height: 200px;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            resize: vertical;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.4;
        }
        
        .preview {
            padding: 48px;
            width: 960px;
            height: 1280px;
            background-color: #000000;
            box-sizing: border-box;
            margin: 0 auto;
            transform: scale(0.5);
            transform-origin: top left;
        }
        
        .preview-container {
            width: 480px;
            height: 640px;
            overflow-y: auto;
            overflow-x: hidden;
            margin: 0 auto;
            background-color: #000000;
            border: 2px solid #ddd;
            border-radius: 8px;
        }

        #preview.preview {
            background-color: inherit;
            position: relative;
        }

        .preview * {
            background-color: transparent;
        }
        
        /* 双栏预览样式 */
        .dual-preview {
            display: flex;
            width: 100%;
            height: 100%;
        }
        
        .preview-left {
            flex: 0.6;
            padding: 20px;
            border-right: 2px solid rgba(255,255,255,0.2);
        }
        
        .preview-right {
            flex: 0.4;
            padding: 20px;
        }
        
        .exported-images {
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .exported-image {
            width: 200px;
            cursor: pointer;
            position: relative;
        }
        
        .exported-image img {
            width: 100%;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .clear-images {
            padding: 8px 16px;
            background: #f44336;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            height: 40px;
            font-size: 14px;
            line-height: 24px;
        }
        
        .clear-images:hover {
            background: #d32f2f;
        }
        
        .image-actions {
            margin-top: 15px;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        button {
            padding: 12px 24px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: background-color 0.3s;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        .controls {
            margin: 20px 0;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .color-preset {
            display: inline-block;
            width: 20px;
            height: 20px;
            margin-left: 5px;
            border: 1px solid #ddd;
            cursor: pointer;
            border-radius: 3px;
        }
        
        .color-preset:hover {
            transform: scale(1.1);
            box-shadow: 0 0 5px rgba(0,0,0,0.3);
        }
        
        .style-controls {
            margin-top: 20px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        
        .style-controls label {
            display: block;
            margin: 8px 0;
        }

        /* 双栏样式容器 */
        .dual-style-container {
            display: flex;
            gap: 20px;
            margin-top: 15px;
        }

        .style-column {
            flex: 1;
            min-width: 0;
        }

        .style-column h4 {
            margin: 0 0 12px 0;
            color: #555;
            font-size: 14px;
            font-weight: bold;
            border-bottom: 1px solid #e9ecef;
            padding-bottom: 6px;
        }

        .style-column label {
            margin: 6px 0;
            font-size: 13px;
        }
        
        .font-controls {
            margin-top: 20px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        
        .font-controls label {
            display: block;
            margin: 12px 0;
        }
        
        .font-controls input[type="range"] {
            width: 200px;
            margin-right: 10px;
        }
        
        input[type="color"] {
            width: 40px;
            height: 30px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
        }
        
        select {
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
        }
        
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        
        h3 {
            color: #555;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <h1>双栏Markdown转图片工具</h1>
    <div class="container">
        <div class="input-section">
            <h3>输入Markdown内容（用***分隔多张图片）</h3>
            
            <div class="dual-input-container">
                <div class="input-column input-column-left">
                    <div class="column-label">英文内容 (左栏)</div>
                    <textarea id="english-input" placeholder="输入英文Markdown内容..."></textarea>
                </div>
                <div class="input-column input-column-right">
                    <div class="column-label">中文内容 (右栏)</div>
                    <textarea id="chinese-input" placeholder="输入中文Markdown内容..."></textarea>
                </div>
            </div>
            
            <div>
                <button id="export-btn" style="margin-top: 16px;">导出图片</button>
            </div>
            
            <div class="style-controls">
                <h3>全局样式设置</h3>
                <div style="margin-top: 14px; display: flex;">
                    <label for="preset-select">预设样式 </label>
                    <select id="preset-select" style="margin-left: 36px;">
                        <option value="">自定义</option>
                    </select>
                </div>
                <div style="margin: 10px 0;display:flex;">
                    <label><input type="radio" name="bg-type" value="color" checked> 背景颜色</label>
                    <label style="margin-left: 20px;"><input type="radio" name="bg-type" value="image"> 背景图片（建议3:4，960x1280分辨率）</label>
                </div>
                <div id="bg-color-controls" class="controls">    
                    <label for="bg-color">背景颜色</label>                
                    <input type="color" id="bg-color" value="#000000" style="margin-left: 32px;">                    
                    <span class="color-preset" style="background:#000000" data-color="#000000" title="黑色"></span>
                    <span class="color-preset" style="background:#293931" data-color="#293931" title="墨绿"></span>
                    <span class="color-preset" style="background:#383329" data-color="#383329" title="深褐"></span>
                </div>
                <div id="bg-image-controls" style="display: none;">
                    <input type="file" id="bg-image-input" accept=".jpg,.jpeg,.png" style="display: none;">
                    <button id="upload-bg-btn" style="margin-top: 10px;">上传背景图片</button>
                    <select id="bg-select" style="margin-top: 10px; margin-left: 10px; display: none;">
                        <option value="">选择已有背景图片</option>
                    </select>
                </div>
            </div>

            <div class="style-controls">
                <h3>双栏样式设置</h3>
                <div class="dual-style-container">
                    <div class="style-column">
                        <h4>左栏（英文）样式</h4>
                        <label>
                            基础文字颜色 
                            <input type="color" id="english-text-color" value="#ffffff" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            一级标题颜色 
                            <input type="color" id="english-h1-color" value="#EFF226" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            二级标题颜色 
                            <input type="color" id="english-h2-color" value="#F3F59E" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            其他标题颜色 
                            <input type="color" id="english-other-heading-color" value="#FDFFD1" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            加粗文字颜色 
                            <input type="color" id="english-bold-color" value="#EFF226" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            斜体文字颜色 
                            <input type="color" id="english-italic-color" value="#E01A1A" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            基础字体大小 (18-58px):
                            <input type="range" id="english-base-font" min="18" max="58" value="30" step="1">
                            <span id="english-base-font-value">30px</span>
                        </label>
                        <label>
                            行间距 (1.0-2.5倍):
                            <input type="range" id="english-line-height" min="10" max="25" value="12" step="1">
                            <span id="english-line-height-value">1.2倍</span>
                        </label>
                    </div>
                    
                    <div class="style-column">
                        <h4>右栏（中文）样式</h4>
                        <label>
                            基础文字颜色 
                            <input type="color" id="chinese-text-color" value="#ffffff" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            一级标题颜色 
                            <input type="color" id="chinese-h1-color" value="#FF6B6B" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            二级标题颜色 
                            <input type="color" id="chinese-h2-color" value="#FFD93D" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            其他标题颜色 
                            <input type="color" id="chinese-other-heading-color" value="#6BCB77" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            加粗文字颜色 
                            <input type="color" id="chinese-bold-color" value="#4D96FF" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            斜体文字颜色 
                            <input type="color" id="chinese-italic-color" value="#9B5DE5" style="margin-left: 6px;">                    
                        </label>
                        <label>
                            基础字体大小 (18-58px):
                            <input type="range" id="chinese-base-font" min="18" max="58" value="23" step="1">
                            <span id="chinese-base-font-value">23px</span>
                        </label>
                        <label>
                            行间距 (1.0-2.5倍):
                            <input type="range" id="chinese-line-height" min="10" max="25" value="15" step="1">
                            <span id="chinese-line-height-value">1.5倍</span>
                        </label>
                    </div>
                </div>
            </div>

            <div class="font-controls">
                <h3>字体设置</h3>
                <div class="dual-style-container">
                    <div class="style-column">
                        <h4>左栏（英文）字体</h4>
                        <label for="english-font-family">选择字体: </label>
                        <select id="english-font-family" style="margin-left: 10px;">
                            <option value="Times New Roman">Times New Roman</option>
                            <option value="Arial">Arial</option>
                            <option value="Microsoft YaHei">微软雅黑</option>
                            <option value="SimSun">宋体</option>
                            <option value="KaiTi">楷体</option>
                            <option value="FangSong">仿宋</option>
                            <option value="SimHei">黑体</option>
                        </select>
                    </div>
                    
                    <div class="style-column">
                        <h4>右栏（中文）字体</h4>
                        <label for="chinese-font-family">选择字体: </label>
                        <select id="chinese-font-family" style="margin-left: 10px;">
                            <option value="Microsoft YaHei">微软雅黑</option>
                            <option value="SimSun">宋体</option>
                            <option value="KaiTi">楷体</option>
                            <option value="FangSong">仿宋</option>
                            <option value="SimHei">黑体</option>
                            <option value="Arial">Arial</option>
                            <option value="Times New Roman">Times New Roman</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="output-section">
            <h3>预览</h3>
            <div class="preview-container">
                <div id="preview" class="preview">
                    <div class="dual-preview">
                        <div class="preview-left" id="preview-left"></div>
                        <div class="preview-right" id="preview-right"></div>
                    </div>
                </div>
            </div>
            
            <h3 id="generated-images-title" style="display:none;margin-top:20px;">以下为生成的图片</h3>
            <div class="exported-images" id="exported-images"></div>
            
            <div class="music-style" style="margin-top:16px;display:none">
                <label>视频音乐类型:</label>
                <p><label><input type="radio" name="music_style" value="modern" checked> 现代</label>
                <label><input type="radio" name="music_style" value="traditional"> 传统</label>
                </p>
                <p>
                <label><input type="radio" name="music_style" value="custom"> 自己上传音乐<span style="font-size: 12px;">（可上传MP3或MP4格式，如果为MP4格式，则自动提取音频。）</span></label>
                </p>
            </div>
            <div id="custom-music-controls" style="display:none; margin-top:10px;">
                <input type="file" id="music-file" accept=".mp3,.mp4" style="display:none">
                <button id="upload-music-btn">选择音乐文件</button>
                <span id="selected-music-name"></span>
            </div>
            <div class="time-per-pic" style="margin-top:16px;display:none">
                <label>
                    每张图片时间 (3-8秒):
                    <input type="range" id="time-per-pic" min="3" max="8" value="4" step="1">
                    <span id="time-per-pic-value">4秒</span>
                </label>
            </div>
            <div class="image-actions">
                <button class="clear-images" id="clear-images">清除所有图片</button>
                <button class="generate-video" id="generate-video" style="display:none">将图片转为视频</button>
                <span id="generating-text" style="display:none;margin-left:10px;color:#ca0b0b;">正在生成视频...</span>
            </div>
        </div>
    </div>

    <script>
        // 预设样式
        let stylePresets = {};
        
        // 加载预设样式
        async function loadPresets() {
            try {
                const response = await fetch('/static/config/preset_styles.json');
                const data = await response.json();
                stylePresets = {};
                data.presets.forEach(preset => {
                    stylePresets[preset.name] = preset;
                });
            } catch (error) {
                console.error('加载预设样式失败:', error);
            }
        }
        
        // 应用预设样式
        function applyPreset(presetName) {
            const preset = stylePresets[presetName];
            if (!preset) return;
            
            // 设置背景颜色
            bgColorInput.value = preset.bgColor;
            
            // 设置左栏（英文）样式
            englishTextColorInput.value = preset.textColor;
            englishH1ColorInput.value = preset.h1Color;
            englishH2ColorInput.value = preset.h2Color;
            englishOtherHeadingColorInput.value = preset.otherHeadingColor;
            englishBoldColorInput.value = preset.boldColor;
            englishItalicColorInput.value = preset.italicColor;
            englishBaseFontInput.value = preset.baseFont;
            
            // 设置右栏（中文）样式 - 使用相同的预设值，但保持中文默认字体大小23
            chineseTextColorInput.value = preset.textColor;
            chineseH1ColorInput.value = preset.h1Color;
            chineseH2ColorInput.value = preset.h2Color;
            chineseOtherHeadingColorInput.value = preset.otherHeadingColor;
            chineseBoldColorInput.value = preset.boldColor;
            chineseItalicColorInput.value = preset.italicColor;
            // 保持中文默认字体大小为23，不跟随预设的baseFont
            chineseBaseFontInput.value = 23;
            
            // 更新显示值
            englishBaseFontValue.textContent = `${preset.baseFont}px`;
            chineseBaseFontValue.textContent = `23px`;
            
            // 更新currentStyles对象
            currentStyles.englishTextColor = preset.textColor;
            currentStyles.englishH1Color = preset.h1Color;
            currentStyles.englishH2Color = preset.h2Color;
            currentStyles.englishOtherHeadingColor = preset.otherHeadingColor;
            currentStyles.englishBoldColor = preset.boldColor;
            currentStyles.englishItalicColor = preset.italicColor;
            
            currentStyles.chineseTextColor = preset.textColor;
            currentStyles.chineseH1Color = preset.h1Color;
            currentStyles.chineseH2Color = preset.h2Color;
            currentStyles.chineseOtherHeadingColor = preset.otherHeadingColor;
            currentStyles.chineseBoldColor = preset.boldColor;
            currentStyles.chineseItalicColor = preset.italicColor;

            // 直接应用样式到当前预览内容，而不是重新解析Markdown
            applyStyles();
            updateEnglishFontSizes();
            updateChineseFontSizes();
            updateBackgroundColor();
            
            // 如果预览中有内容，确保样式正确应用
            if (previewLeft.innerHTML || previewRight.innerHTML) {
                applyStyles();
            }
        }

        // 动态加载预设选项
        async function loadPresetOptions() {
            try {
                const response = await fetch('/static/config/preset_styles.json');
                const data = await response.json();
                const presetSelect = document.getElementById('preset-select');
                
                // 清空现有选项（保留"自定义"选项）
                while (presetSelect.options.length > 1) {
                    presetSelect.remove(1);
                }
                
                // 添加从JSON加载的选项
                data.presets.forEach(preset => {
                    const option = document.createElement('option');
                    option.value = preset.name;
                    option.textContent = preset.name;
                    presetSelect.appendChild(option);
                });
                
                // 设置默认选中"黑色经典"
                presetSelect.value = '黑色经典';
                return data.presets;
            } catch (error) {
                console.error('加载预设选项失败:', error);
                return [];
            }
        }
        
        // 初始化样式
        let currentStyles = {
            // 左栏（英文）样式
            englishTextColor: '#ffffff',
            englishH1Color: '#EFF226',
            englishH2Color: '#F3F59E',
            englishOtherHeadingColor: '#FDFFD1',
            englishBoldColor: '#EFF226',
            englishItalicColor: '#E01A1A',
            englishFontFamily: 'Times New Roman',
            
            // 右栏（中文）样式
            chineseTextColor: '#ffffff',
            chineseH1Color: '#FF6B6B',
            chineseH2Color: '#FFD93D',
            chineseOtherHeadingColor: '#6BCB77',
            chineseBoldColor: '#4D96FF',
            chineseItalicColor: '#9B5DE5',
            chineseFontFamily: 'Microsoft YaHei',
            
            // 全局样式
            underlineColor: '#ffffff'
        };

        // 存储当前背景图片URL
        let currentBgImageUrl = null;

        // 获取DOM元素
        const englishInput = document.getElementById('english-input');
        const chineseInput = document.getElementById('chinese-input');
        const previewLeft = document.getElementById('preview-left');
        const previewRight = document.getElementById('preview-right');
        const exportBtn = document.getElementById('export-btn');
        const bgColorInput = document.getElementById('bg-color');
        
        // 左栏样式控件
        const englishTextColorInput = document.getElementById('english-text-color');
        const englishH1ColorInput = document.getElementById('english-h1-color');
        const englishH2ColorInput = document.getElementById('english-h2-color');
        const englishOtherHeadingColorInput = document.getElementById('english-other-heading-color');
        const englishBoldColorInput = document.getElementById('english-bold-color');
        const englishItalicColorInput = document.getElementById('english-italic-color');
        
        // 右栏样式控件
        const chineseTextColorInput = document.getElementById('chinese-text-color');
        const chineseH1ColorInput = document.getElementById('chinese-h1-color');
        const chineseH2ColorInput = document.getElementById('chinese-h2-color');
        const chineseOtherHeadingColorInput = document.getElementById('chinese-other-heading-color');
        const chineseBoldColorInput = document.getElementById('chinese-bold-color');
        const chineseItalicColorInput = document.getElementById('chinese-italic-color');
        
        // 独立字体大小控件
        const englishBaseFontInput = document.getElementById('english-base-font');
        const chineseBaseFontInput = document.getElementById('chinese-base-font');
        const englishBaseFontValue = document.getElementById('english-base-font-value');
        const chineseBaseFontValue = document.getElementById('chinese-base-font-value');
        
        // 独立字体控件
        const englishFontFamilyInput = document.getElementById('english-font-family');
        const chineseFontFamilyInput = document.getElementById('chinese-font-family');
        
        // 行间距控件
        const englishLineHeightInput = document.getElementById('english-line-height');
        const chineseLineHeightInput = document.getElementById('chinese-line-height');
        const englishLineHeightValue = document.getElementById('english-line-height-value');
        const chineseLineHeightValue = document.getElementById('chinese-line-height-value');

        // 初始化滑块显示
        englishBaseFontValue.textContent = `${englishBaseFontInput.value}px`;
        chineseBaseFontValue.textContent = `${chineseBaseFontInput.value}px`;
        
        // 初始化行间距显示
        englishLineHeightValue.textContent = `${(englishLineHeightInput.value / 10).toFixed(1)}倍`;
        chineseLineHeightValue.textContent = `${(chineseLineHeightInput.value / 10).toFixed(1)}倍`;

        // 监听输入变化
        englishInput.addEventListener('input', updatePreview);
        chineseInput.addEventListener('input', updatePreview);

        // 监听左栏样式变化
        englishTextColorInput.addEventListener('input', updateEnglishStyles);
        englishH1ColorInput.addEventListener('input', updateEnglishStyles);
        englishH2ColorInput.addEventListener('input', updateEnglishStyles);
        englishOtherHeadingColorInput.addEventListener('input', updateEnglishStyles);
        englishBoldColorInput.addEventListener('input', updateEnglishStyles);
        englishItalicColorInput.addEventListener('input', updateEnglishStyles);
        
        // 监听右栏样式变化
        chineseTextColorInput.addEventListener('input', updateChineseStyles);
        chineseH1ColorInput.addEventListener('input', updateChineseStyles);
        chineseH2ColorInput.addEventListener('input', updateChineseStyles);
        chineseOtherHeadingColorInput.addEventListener('input', updateChineseStyles);
        chineseBoldColorInput.addEventListener('input', updateChineseStyles);
        chineseItalicColorInput.addEventListener('input', updateChineseStyles);
        
        // 监听独立字体大小变化
        englishBaseFontInput.addEventListener('input', updateEnglishFontSizes);
        chineseBaseFontInput.addEventListener('input', updateChineseFontSizes);
        
        // 监听字体变化
        englishFontFamilyInput.addEventListener('change', updateEnglishFontFamily);
        chineseFontFamilyInput.addEventListener('change', updateChineseFontFamily);
        
        // 监听行间距变化
        englishLineHeightInput.addEventListener('input', updateEnglishLineHeight);
        chineseLineHeightInput.addEventListener('input', updateChineseLineHeight);

        // 添加预设颜色点击事件
        document.querySelectorAll('.color-preset').forEach(preset => {
            preset.addEventListener('click', () => {
                bgColorInput.value = preset.dataset.color;
                updateBackgroundColor();
            });
        });

        // 获取新增的DOM元素
        const bgTypeRadios = document.querySelectorAll('input[name="bg-type"]');
        const bgColorControls = document.getElementById('bg-color-controls');
        const bgImageControls = document.getElementById('bg-image-controls');
        const bgImageInput = document.getElementById('bg-image-input');
        const uploadBgBtn = document.getElementById('upload-bg-btn');
        
        // 背景类型切换事件
        bgTypeRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'color') {
                    bgColorControls.style.display = 'flex';
                    bgImageControls.style.display = 'none';
                } else {
                    bgColorControls.style.display = 'none';
                    bgImageControls.style.display = 'block';
                }
                updateBackgroundColor();
            });
        });

        // 上传背景图片按钮点击事件
        uploadBgBtn.addEventListener('click', function() {
            bgImageInput.click();
        });

        // 背景图片选择事件
        bgImageInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    currentBgImageUrl = event.target.result;
                    updateBackgroundColor(currentBgImageUrl);
                }
                reader.readAsDataURL(e.target.files[0]);
            }
        });

        bgColorInput.addEventListener('input', updateBackgroundColor);

        // 更新背景颜色/图片
        function updateBackgroundColor(bgImageUrl) {
            const previewContainer = document.querySelector('.preview-container');
            const preview = document.getElementById('preview');
            
            if (document.querySelector('input[name="bg-type"]:checked').value === 'color') {
                const bgColor = bgColorInput.value;
                previewContainer.style.backgroundImage = 'none';
                previewContainer.style.backgroundColor = bgColor;
                preview.style.backgroundImage = 'none';
                preview.style.backgroundColor = bgColor;
            } else {
                const imageUrl = bgImageUrl || currentBgImageUrl;
                if (imageUrl) {
                    previewContainer.style.backgroundColor = 'transparent';
                    previewContainer.style.backgroundImage = `url(${imageUrl})`;
                    previewContainer.style.backgroundSize = 'cover';
                    preview.style.backgroundColor = 'transparent';
                    preview.style.backgroundImage = `url(${imageUrl})`;
                    preview.style.backgroundSize = 'cover';
                }
            }
        }

        // 更新预览
        function updatePreview() {
            const englishMarkdown = englishInput.value;
            const chineseMarkdown = chineseInput.value;
            
            previewLeft.innerHTML = marked.parse(englishMarkdown);
            previewRight.innerHTML = marked.parse(chineseMarkdown);
            
            applyStyles();
        }


        // 更新左栏样式
        function updateEnglishStyles() {
            // 更新左栏样式设置
            currentStyles.englishTextColor = englishTextColorInput.value;
            currentStyles.englishH1Color = englishH1ColorInput.value;
            currentStyles.englishH2Color = englishH2ColorInput.value;
            currentStyles.englishOtherHeadingColor = englishOtherHeadingColorInput.value;
            currentStyles.englishBoldColor = englishBoldColorInput.value;
            currentStyles.englishItalicColor = englishItalicColorInput.value;
            
            // 强制重新渲染当前内容
            const currentEnglish = previewLeft.innerHTML;
            const currentChinese = previewRight.innerHTML;
            previewLeft.innerHTML = '';
            previewRight.innerHTML = '';
            setTimeout(() => {
                previewLeft.innerHTML = currentEnglish;
                previewRight.innerHTML = currentChinese;
                applyStyles();
            }, 0);
        }

        // 更新右栏样式
        function updateChineseStyles() {
            // 更新右栏样式设置
            currentStyles.chineseTextColor = chineseTextColorInput.value;
            currentStyles.chineseH1Color = chineseH1ColorInput.value;
            currentStyles.chineseH2Color = chineseH2ColorInput.value;
            currentStyles.chineseOtherHeadingColor = chineseOtherHeadingColorInput.value;
            currentStyles.chineseBoldColor = chineseBoldColorInput.value;
            currentStyles.chineseItalicColor = chineseItalicColorInput.value;
            
            // 强制重新渲染当前内容
            const currentEnglish = previewLeft.innerHTML;
            const currentChinese = previewRight.innerHTML;
            previewLeft.innerHTML = '';
            previewRight.innerHTML = '';
            setTimeout(() => {
                previewLeft.innerHTML = currentEnglish;
                previewRight.innerHTML = currentChinese;
                applyStyles();
            }, 0);
        }


        // 更新左栏字体大小
        function updateEnglishFontSizes() {
            const englishBaseFont = parseInt(englishBaseFontInput.value);
            
            if (!isNaN(englishBaseFont) && englishBaseFont >= 18 && englishBaseFont <= 58) {
                englishBaseFontValue.textContent = `${englishBaseFont}px`;
                previewLeft.style.fontSize = `${englishBaseFont}px`;
            }
        }

        // 更新右栏字体大小
        function updateChineseFontSizes() {
            const chineseBaseFont = parseInt(chineseBaseFontInput.value);
            
            if (!isNaN(chineseBaseFont) && chineseBaseFont >= 18 && chineseBaseFont <= 58) {
                chineseBaseFontValue.textContent = `${chineseBaseFont}px`;
                previewRight.style.fontSize = `${chineseBaseFont}px`;
            }
        }

        // 更新左栏字体
        function updateEnglishFontFamily() {
            currentStyles.englishFontFamily = englishFontFamilyInput.value;
            previewLeft.style.fontFamily = currentStyles.englishFontFamily;
        }

        // 更新右栏字体
        function updateChineseFontFamily() {
            currentStyles.chineseFontFamily = chineseFontFamilyInput.value;
            previewRight.style.fontFamily = currentStyles.chineseFontFamily;
        }

        // 更新左栏行间距
        function updateEnglishLineHeight() {
            const lineHeightValue = englishLineHeightInput.value / 10;
            englishLineHeightValue.textContent = `${lineHeightValue.toFixed(1)}倍`;
            previewLeft.style.lineHeight = lineHeightValue;
        }

        // 更新右栏行间距
        function updateChineseLineHeight() {
            const lineHeightValue = chineseLineHeightInput.value / 10;
            chineseLineHeightValue.textContent = `${lineHeightValue.toFixed(1)}倍`;
            previewRight.style.lineHeight = lineHeightValue;
        }

        // 应用样式
        function applyStyles() {
            // 基础字体样式 - 使用独立字体设置
            previewLeft.style.fontFamily = currentStyles.englishFontFamily;
            previewRight.style.fontFamily = currentStyles.chineseFontFamily;
            
            // 应用字体大小
            const englishBaseFont = parseInt(englishBaseFontInput.value);
            const chineseBaseFont = parseInt(chineseBaseFontInput.value);
            previewLeft.style.fontSize = `${englishBaseFont}px`;
            previewRight.style.fontSize = `${chineseBaseFont}px`;
            
            // 应用行间距
            previewLeft.style.lineHeight = englishLineHeightInput.value / 10;
            previewRight.style.lineHeight = chineseLineHeightInput.value / 10;
            
            // 分别应用左右栏颜色
            previewLeft.style.color = currentStyles.englishTextColor;
            previewRight.style.color = currentStyles.chineseTextColor;
            
            // 标题样式
            applyHeadingStyles(previewLeft, 'english');
            applyHeadingStyles(previewRight, 'chinese');
            
            // 加粗样式
            applyBoldStyles(previewLeft, 'english');
            applyBoldStyles(previewRight, 'chinese');
            
            // 斜体样式
            applyItalicStyles(previewLeft, 'english');
            applyItalicStyles(previewRight, 'chinese');
        }

        function applyHeadingStyles(container, columnType) {
            const h1s = container.querySelectorAll('h1');
            h1s.forEach(h => {
                h.style.color = columnType === 'english' ? currentStyles.englishH1Color : currentStyles.chineseH1Color;
            });

            const h2s = container.querySelectorAll('h2');
            h2s.forEach(h => {
                h.style.color = columnType === 'english' ? currentStyles.englishH2Color : currentStyles.chineseH2Color;
            });

            const otherHeadings = container.querySelectorAll('h3, h4, h5, h6');
            otherHeadings.forEach(h => {
                h.style.color = columnType === 'english' ? currentStyles.englishOtherHeadingColor : currentStyles.chineseOtherHeadingColor;
            });
        }

        function applyBoldStyles(container, columnType) {
            const boldElements = container.querySelectorAll('strong, b');
            boldElements.forEach(el => {
                el.style.color = columnType === 'english' ? currentStyles.englishBoldColor : currentStyles.chineseBoldColor;
            });
        }

        function applyItalicStyles(container, columnType) {
            const italicElements = container.querySelectorAll('em, i');
            italicElements.forEach(el => {
                el.style.color = columnType === 'english' ? currentStyles.englishItalicColor : currentStyles.chineseItalicColor;
                el.style.fontStyle = 'italic';
            });
        }

        // 获取导出图片容器和按钮
        const exportedImagesContainer = document.getElementById('exported-images');
        const clearImagesBtn = document.getElementById('clear-images');
        const generatedImagesTitle = document.getElementById('generated-images-title');

        // 清除所有图片
        clearImagesBtn.addEventListener('click', () => {
            exportedImagesContainer.innerHTML = '';
            generatedImagesTitle.style.display = 'none';
        });

        // 导出按钮点击事件
        exportBtn.addEventListener('click', exportToImage);

        // 检测分隔线并分割内容（仅支持***分隔符）
        function splitContentBySeparator(content) {
            const sections = content.split('***');
            return sections.filter(section => section.trim() !== '');
        }

        // 导出为图片
        async function exportToImage() {
            const bgType = document.querySelector('input[name="bg-type"]:checked').value;
            
            // 清除之前的图片
            exportedImagesContainer.innerHTML = '';
            generatedImagesTitle.style.display = 'none';
            
            const englishMarkdown = englishInput.value;
            const chineseMarkdown = chineseInput.value;
            
            // 分割内容
            const englishParts = splitContentBySeparator(englishMarkdown);
            const chineseParts = splitContentBySeparator(chineseMarkdown);
            
            const maxParts = Math.max(englishParts.length, chineseParts.length);
            
            // 为每个部分创建图片
            for (let i = 0; i < maxParts; i++) {
                const englishPart = englishParts[i] || '';
                const chinesePart = chineseParts[i] || '';
                
                // 创建临时预览容器
                const tempPreview = document.createElement('div');
                tempPreview.className = 'preview';
                tempPreview.style.width = '960px';
                tempPreview.style.height = '1280px';
                tempPreview.style.padding = '48px';
                tempPreview.style.boxSizing = 'border-box';
                
                // 复制双栏内容
                const dualPreview = document.createElement('div');
                dualPreview.className = 'dual-preview';
                
                const leftCol = document.createElement('div');
                leftCol.className = 'preview-left';
                leftCol.innerHTML = marked.parse(englishPart);
                
                const rightCol = document.createElement('div');
                rightCol.className = 'preview-right';
                rightCol.innerHTML = marked.parse(chinesePart);
                
                dualPreview.appendChild(leftCol);
                dualPreview.appendChild(rightCol);
                tempPreview.appendChild(dualPreview);
                
                // 设置背景
                if (bgType === 'color') {
                    tempPreview.style.backgroundColor = bgColorInput.value;
                } else if (currentBgImageUrl) {
                    tempPreview.style.backgroundImage = `url(${currentBgImageUrl})`;
                    tempPreview.style.backgroundSize = 'cover';
                }
                
                // 应用样式
                document.body.appendChild(tempPreview);
                applyStylesToElement(tempPreview);
                
                // 确保样式应用完成
                await new Promise(resolve => setTimeout(resolve, 100));
                
                // 转换为图片
                const canvas = await html2canvas(tempPreview, {
                    scale: 2,
                    logging: true,
                    useCORS: true,
                    backgroundColor: null
                });
                
                // 创建图片展示元素
                const imageContainer = document.createElement('div');
                imageContainer.className = 'exported-image';
                
                const img = document.createElement('img');
                img.src = canvas.toDataURL('image/png');
                img.alt = `双栏Markdown图片 ${i + 1}`;
                
                imageContainer.appendChild(img);
                exportedImagesContainer.appendChild(imageContainer);
                
                // 移除临时预览
                document.body.removeChild(tempPreview);
            }
            
            // 显示标题
            if (maxParts > 0) {
                generatedImagesTitle.style.display = 'block';
            }
        }

        // 为元素应用样式
        function applyStylesToElement(element) {
            const leftCol = element.querySelector('.preview-left');
            const rightCol = element.querySelector('.preview-right');
            
            if (leftCol) {
                // 使用独立字体大小设置
                const englishBaseFont = parseInt(englishBaseFontInput.value);
                leftCol.style.fontSize = `${englishBaseFont}px`;
                leftCol.style.fontFamily = currentStyles.englishFontFamily;
                leftCol.style.color = currentStyles.englishTextColor;
                leftCol.style.lineHeight = englishLineHeightInput.value / 10;
                applyHeadingStyles(leftCol, 'english');
                applyBoldStyles(leftCol, 'english');
                applyItalicStyles(leftCol, 'english');
            }
            
            if (rightCol) {
                // 使用独立字体大小设置
                const chineseBaseFont = parseInt(chineseBaseFontInput.value);
                rightCol.style.fontSize = `${chineseBaseFont}px`;
                rightCol.style.fontFamily = currentStyles.chineseFontFamily;
                rightCol.style.color = currentStyles.chineseTextColor;
                rightCol.style.lineHeight = chineseLineHeightInput.value / 10;
                applyHeadingStyles(rightCol, 'chinese');
                applyBoldStyles(rightCol, 'chinese');
                applyItalicStyles(rightCol, 'chinese');
            }
        }

        // 获取预设选择器
        const presetSelect = document.getElementById('preset-select');
        
        // 监听预设选择变化
        presetSelect.addEventListener('change', (e) => {
            if (e.target.value) {
                applyPreset(e.target.value);
            }
        });

        // 监听样式变化自动切换到自定义
        const styleInputs = [
            englishTextColorInput, englishH1ColorInput, englishH2ColorInput, englishOtherHeadingColorInput,
            englishBoldColorInput, englishItalicColorInput, englishBaseFontInput,
            chineseTextColorInput, chineseH1ColorInput, chineseH2ColorInput, chineseOtherHeadingColorInput,
            chineseBoldColorInput, chineseItalicColorInput, chineseBaseFontInput,
            bgColorInput
        ];
        
        styleInputs.forEach(input => {
            input.addEventListener('input', () => {
                if (presetSelect.value !== '') {
                    presetSelect.value = '';
                }
            });
        });

        // 获取视频生成相关元素
        const generateVideoBtn = document.getElementById('generate-video');
        const generatingText = document.getElementById('generating-text');
        const timePerPicInput = document.getElementById('time-per-pic');
        const timePerPicValue = document.getElementById('time-per-pic-value');

        // 初始化每张图片时间滑块
        timePerPicValue.textContent = `${timePerPicInput.value}秒`;
        timePerPicInput.addEventListener('input', () => {
            timePerPicValue.textContent = `${timePerPicInput.value}秒`;
        });

        // 监听图片容器变化，显示/隐藏视频生成按钮
        const observer = new MutationObserver(() => {
            const hasImages = exportedImagesContainer.children.length > 0;
            generateVideoBtn.style.display = hasImages ? 'block' : 'none';
            generatedImagesTitle.style.display = hasImages ? 'block' : 'none';
            document.querySelector('.music-style').style.display = hasImages ? 'block' : 'none';
            document.querySelector('.time-per-pic').style.display = hasImages ? 'block' : 'none';
        });
        
        // 初始隐藏音乐类型选择和时间控制
        document.querySelector('.music-style').style.display = 'none';
        document.querySelector('.time-per-pic').style.display = 'none';
        observer.observe(exportedImagesContainer, { childList: true });

        // 自定义音乐上传逻辑
        const musicStyleRadios = document.querySelectorAll('input[name="music_style"]');
        const customMusicControls = document.getElementById('custom-music-controls');
        const musicFileInput = document.getElementById('music-file');
        const uploadMusicBtn = document.getElementById('upload-music-btn');
        const selectedMusicName = document.getElementById('selected-music-name');

        // 监听音乐类型变化
        musicStyleRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                customMusicControls.style.display = this.value === 'custom' ? 'block' : 'none';
            });
        });

        // 上传音乐按钮点击事件
        uploadMusicBtn.addEventListener('click', function() {
            musicFileInput.click();
        });

        // 音乐文件选择事件
        musicFileInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const file = e.target.files[0];
                // 验证文件类型
                if (!file.type.match('audio/mp3') && !file.type.match('audio/mp4') && 
                    !file.name.toLowerCase().endsWith('.mp3') && !file.name.toLowerCase().endsWith('.mp4')) {
                    alert('请选择MP3或MP4格式的音乐文件');
                    musicFileInput.value = '';
                    selectedMusicName.textContent = '';
                    return;
                }
                selectedMusicName.textContent = file.name;
                selectedMusicName.style.marginLeft = '10px';
            }
        });

        // 获取音乐文件数据
        function getMusicFileData() {
            if (document.querySelector('input[name="music_style"]:checked').value === 'custom' && 
                musicFileInput.files && musicFileInput.files[0]) {
                return new Promise((resolve) => {
                    const file = musicFileInput.files[0];
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        const content = e.target.result.split(',')[1]; // 获取base64内容部分
                        resolve({
                            name: file.name,
                            type: file.type,
                            size: file.size,
                            content: content // 添加base64编码的文件内容
                        });
                    };
                    
                    reader.readAsDataURL(file); // 读取为DataURL
                });
            }
            return Promise.resolve(null);
        }

        // 生成视频按钮点击事件
        generateVideoBtn.addEventListener('click', async () => {
            const images = Array.from(exportedImagesContainer.querySelectorAll('img')).map(img => img.src);
            
            try {
                // 显示"正在生成"文本
                generatingText.style.display = 'inline';
                generateVideoBtn.disabled = true;
                
                // 获取音乐文件数据
                const musicData = await getMusicFileData();
                
                const requestData = {
                    images: images,
                    resolution: '960x1280',
                    music_style: document.querySelector('input[name="music_style"]:checked').value,
                    music_file_data: musicData,
                    time_per_pic: document.getElementById('time-per-pic').value
                };

                const response = await fetch('/md_pic_to_video', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                if (response.ok) {
                    // 获取视频blob数据
                    const blob = await response.blob();
                    // 创建下载链接
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'dual_column_video.mp4';
                    document.body.appendChild(a);
                    a.click();
                    // 清理
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                } else {
                    throw new Error('视频生成失败');
                }
            } catch (error) {
                console.error('生成视频出错:', error);
                alert('生成视频时出错: ' + error.message);
            } finally {
                // 隐藏"正在生成"文本
                generatingText.style.display = 'none';
                generateVideoBtn.disabled = false;
            }
        });

        // 加载背景图片列表
        async function loadBackgroundImages() {
            try {
                const response = await fetch('/get_ddstudy_bg_list');
                const data = await response.json();
                
                // console.log('背景图片数据:', data); // 先console.log查看后端返回的数据
                
                if (data.res === 'ok') {
                    buildBackgroundSelect(data.data);
                } else {
                    console.error('获取背景图片列表失败');
                }
            } catch (error) {
                console.error('加载背景图片列表失败:', error);
            }
        }

        // 构建背景图片选择框
        function buildBackgroundSelect(bgData) {
            const bgSelect = document.getElementById('bg-select');
            
            // 清空现有选项（保留默认选项）
            while (bgSelect.options.length > 1) {
                bgSelect.remove(1);
            }
            
            // 添加分类和图片选项
            for (const [category, images] of Object.entries(bgData)) {
                if (images.length > 0) {
                    // 添加分类分组
                    const group = document.createElement('optgroup');
                    group.label = category;
                    
                    // 添加该分类下的所有图片选项
                    images.forEach(imagePath => {
                        const option = document.createElement('option');
                        const fileName = imagePath.split(/[/\\]/).pop(); // 获取文件名
                        // 将本地文件路径转换为服务器可访问的URL
                        const imageUrl = `/serve_bg_image?path=${encodeURIComponent(imagePath)}`;
                        option.value = imageUrl;
                        option.textContent = fileName;
                        group.appendChild(option);
                    });
                    
                    bgSelect.appendChild(group);
                }
            }
            
            // 显示选择框
            bgSelect.style.display = 'inline-block';
            
            // 添加选择事件监听
            bgSelect.addEventListener('change', function() {
                if (this.value) {
                    // 设置当前背景图片URL
                    currentBgImageUrl = this.value;
                    updateBackgroundColor(currentBgImageUrl);
                }
            });
        }

        // 加载预设并初始化
        loadPresets().then(() => {
            loadPresetOptions().then(() => {
                // 应用默认预设
                applyPreset('黑色经典');
                // 加载背景图片列表
                loadBackgroundImages();
            });
        });

        // 初始化预览
        updatePreview();
    </script>
</body>
</html>
